package com.my.activity;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.MenuItem;
import android.widget.*;
import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.my.R;
import com.my.util.ApiUtil;
import com.my.util.SpinnerOption;

import java.util.ArrayList;
import java.util.List;

public class RandUserActivity extends AppCompatActivity {

    EditText count;
    Button submit;
    TextView view;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rand_user);
        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setDisplayShowCustomEnabled(true);
        }
        count = findViewById(R.id.count);
        submit = findViewById(R.id.submit);
        view = findViewById(R.id.view);
        Spinner spinner = findViewById(R.id.grade_class);
        SharedPreferences preferences = this.getSharedPreferences("LOGIN_DATA", Context.MODE_PRIVATE);
        JSONObject user = JSONUtil.parseObj(preferences.getString("user", null));
        Handler handler1 = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                JSONObject rest = ((JSONObject) msg.obj);
                if(rest.getInt("code") == 200) {
                    List<SpinnerOption> towns = new ArrayList<>();
                    for (JSONObject obj : rest.getJSONObject("data").getJSONArray("list").jsonIter()) {
                        towns.add(new SpinnerOption(obj.getLong("gradeClassId"), obj.getStr("gradeName") + obj.getStr("className")));
                    }
                    ArrayAdapter<SpinnerOption> adapter = new ArrayAdapter<SpinnerOption>(RandUserActivity.this, android.R.layout.simple_spinner_item, towns);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
                    spinner.setAdapter(adapter);
                }
            }
        };
        new Thread(() -> {
            Message message = new Message();
            message.obj = JSONUtil.parseObj(HttpUtil.get(ApiUtil.HTTP_ADDRESS + "getByUserIdGradeClass?userId=" + user.getLong("id")));
            handler1.sendMessage(message);
        }).start();
        Handler handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                JSONObject rest = ((JSONObject) msg.obj);
                if(rest.getInt("code") == 200) {
                    StringBuilder sb = new StringBuilder();
                    for (String str : rest.getJSONObject("data").getJSONArray("list").toList(String.class)) {
                        sb.append(str).append(", ");
                    }
                    if(sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 2);
                    }
                    view.setText(sb.toString());
                }
            }
        };
        submit.setOnClickListener(v -> {
            if(spinner.getAdapter().getCount() == 0) {
                Toast.makeText(RandUserActivity.this, "当前没有可管理班级！", Toast.LENGTH_LONG).show();
                return;
            }
            Long classId = ((SpinnerOption) spinner.getSelectedItem()).getValue();
            if(classId == null) {
                Toast.makeText(RandUserActivity.this, "请至少选择一个班级！", Toast.LENGTH_LONG).show();
                return;
            }
            new Thread(() -> {
                Message message = new Message();
                message.obj = JSONUtil.parseObj(HttpUtil.get(ApiUtil.HTTP_ADDRESS + "randUser?count=" + count.getText() + "&classId=" + classId));
                handler.sendMessage(message);
            }).start();
        });
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == 16908332) {
            onBackPressed();
        }
        return super.onOptionsItemSelected(item);
    }
}